const {exec, escape} = require('../db/mysql')

/**
 * 使用对象：教练
 * 根据身份证号 (identify,username) 获取练车时间安排
 * @param username 身份证号
 * @returns {Promise<unknown>}
 */
const getArrangeByUsername = (username) => {
  username = escape(username)
  const sql = `select *
               from arrange
               where identify = ${username}`
  return exec(sql).then(rows => {
    return rows[0] || {}
  })
}
/**
 * 使用对象：教练
 * 添加练车时间安排
 * @param identify 教练身份证号
 * @param name 教练姓名
 * @param start_date 开始练车日期
 * @param end_date 结束练车日期
 * @param start_time 每天开始练车时间
 * @param end_time 每天结束练车时间
 * @param interval_time 练车时间段时长
 * @param number_limit 每个练车时间段的人数限制
 * @returns {Promise<unknown>}
 */
const newArrange = ({identify, name, start_date, end_date, start_time, end_time, interval_time, number_limit}) => {
  identify = escape(identify)
  name = escape(name)
  start_date = escape(start_date)
  end_date = escape(end_date)
  start_time = escape(start_time)
  end_time = escape(end_time)
  interval_time = escape(interval_time)
  number_limit = escape(number_limit)
  const sql = `insert into arrange(identify, name, start_date, end_date, start_time, end_time, interval_time,
                                   number_limit)
               values (${identify}, ${name}, ${start_date}, ${end_date}, ${start_time}, ${end_time}, ${interval_time},
                       ${number_limit})`
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}
/**
 * 使用对象：教练
 * 修改练车时间安排
 * @param id 修改安排记录的编号
 * @param start_date 开始练车日期
 * @param end_date 结束练车日期
 * @param start_time 每天开始练车时间
 * @param end_time 每天结束练车时间
 * @param interval_time 练车时间段时长
 * @param number_limit 每个练车时间段的人数限制
 * @returns {Promise<unknown>}
 */
const updateArrange = ({id, start_date, end_date, start_time, end_time, interval_time, number_limit}) => {
  id = escape(id)
  start_date = escape(start_date)
  end_date = escape(end_date)
  start_time = escape(start_time)
  end_time = escape(end_time)
  interval_time = escape(interval_time)
  number_limit = escape(number_limit)
  const sql = `update arrange
               set start_date    = ${start_date},
                   end_date      = ${end_date},
                   start_time    = ${start_time},
                   end_time      = ${end_time},
                   interval_time = ${interval_time},
                   number_limit  = ${number_limit}
               where id = ${id}`
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

module.exports = {
  getArrangeByUsername,
  newArrange,
  updateArrange
}
